//
//  DDDetailsSpecView.m
//  Dingdong
//
//  Created by 程强 on 16/11/28.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDDetailsSpecView.h"
#import "DDCountBar.h"
#import "DDSpecNormalHeaderView.h"
#import "DDSpecCountHeaderView.h"

@interface DDDetailsSpecView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) UICollectionView *specCollection;
@property (strong, nonatomic) UIImageView *goodsIcon;
@property (strong, nonatomic) KKLabel *priceLbl;
@property (strong, nonatomic) KKLabel *codeLbl;
@property (strong, nonatomic) NSMutableDictionary *selectIndexPath;
@property (strong, nonatomic) NSMutableDictionary *selectSpec;
@property (strong, nonatomic) NSMutableDictionary *selectSpecValue;
@property (strong, nonatomic) DDSpecCountHeaderView *specCountHeader;
@end

static NSString *indentifier = @"SpecValueCell";

@implementation DDDetailsSpecView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = RGBColor(237, 237, 237);
        
        weak_Self(self);
        UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, 90)];
        [self addSubview:topView];
        topView.backgroundColor = [UIColor whiteColor];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf);
            make.width.top.equalTo(weakSelf);
            make.height.equalTo(@90);
        }];
        
        UIView *iconBack = [[UIView alloc]init];
        iconBack.backgroundColor = [UIColor whiteColor];
        [topView addSubview:iconBack];
        iconBack.layer.cornerRadius = 5.0;
        iconBack.layer.borderColor = RGBColor(237, 237, 237).CGColor;
        iconBack.layer.borderWidth = 1.0;
        [iconBack mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.equalTo(@90);
            make.left.equalTo(topView).offset(15);
            make.top.equalTo(topView).offset(-10);
        }];
        
        self.goodsIcon = [[UIImageView alloc]init];
        [iconBack addSubview:_goodsIcon];
        [_goodsIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
        }];
        
        self.priceLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
            lbl.laText(@"",kRedColor,[UIFont systemFontOfSize:18.0],NSTextAlignmentLeft);
        }];
        [topView addSubview:_priceLbl];
        [_priceLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(iconBack.mas_right).offset(15);
            make.top.equalTo(topView).offset(25);
            make.height.equalTo(@30);
            make.width.equalTo(@150);
        }];
        
        self.codeLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
            lbl.laText(@"",RGBColor(100,100,100),[UIFont systemFontOfSize:13.0],NSTextAlignmentLeft);
        }];
        [topView addSubview:_codeLbl];
        [_codeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.priceLbl.mas_bottom);
            make.left.height.equalTo(weakSelf.priceLbl);
            make.right.equalTo(topView).offset(-20);
        }];
        
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        CGFloat width = 80;
        CGFloat height = 20;
        layout.itemSize = CGSizeMake(width, height);
        
        UICollectionView *collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
        collection.delegate = self;
        collection.dataSource = self;
        [collection registerClass:[DDDetailsSpecValueCell class] forCellWithReuseIdentifier:indentifier];
        [collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
        collection.backgroundColor = [UIColor whiteColor];
        [self addSubview:collection];
        collection.scrollEnabled = NO;
        [collection mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topView.mas_bottom).offset(1);
            make.centerX.width.equalTo(weakSelf);
            make.bottom.equalTo(weakSelf).offset(-48);
        }];

        [collection registerClass:[DDSpecNormalHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SpecNormalHeader"];
        [collection registerClass:[DDSpecCountHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SpecCountHeader"];
        
        self.specCollection = collection;
        
        UIButton *buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        buyBtn.backgroundColor = RGBColor(255, 80, 80);
        [buyBtn setTitle:@"Add to cart" forState:UIControlStateNormal];
        [self addSubview:buyBtn];
        [buyBtn addTarget:self action:@selector(addGoodsToCart:) forControlEvents:UIControlEventTouchUpInside];
        [buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf);
            make.width.equalTo(weakSelf);
            make.height.equalTo(@48);
            make.top.equalTo(collection.mas_bottom);
        }];
        
        self.selectIndexPath = [[NSMutableDictionary alloc]initWithCapacity:0];
        self.selectSpec = [[NSMutableDictionary alloc]initWithCapacity:0];
        self.selectSpecValue = [[NSMutableDictionary alloc]initWithCapacity:0];
    }
    return self;
}
- (void)addGoodsToCart:(UIButton *)sender
{
    if (self.selectSpec.count<self.specSet.specList.count) {
        //规格没有选完
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(specView:addGoodsToCart:specValue:)]) {
        [self.delegate specView:self addGoodsToCart:self.selectSpec specValue:self.selectSpecValue];
    }
}
#pragma mark --- UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.specSet.specList.count+1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section<self.specSet.specList.count) {
        DDGoodsSpec *spec = self.specSet.specList[section];
        return spec.valueList.count;
    }else{
        return 0;
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section<self.specSet.specList.count) {
        DDDetailsSpecValueCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:indentifier forIndexPath:indexPath];
        DDGoodsSpec *spec = self.specSet.specList[indexPath.section];
        DDGoodsSpecValue *specValue = spec.valueList[indexPath.row];
        cell.specValue = specValue.spec_value;
        return cell;
    }else{
        return nil;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDGoodsSpec *spec = self.specSet.specList[indexPath.section];
    DDGoodsSpecValue *specValue = spec.valueList[indexPath.row];

    NSString *section = [NSString stringWithFormat:@"%ld",indexPath.section];
    if ([self.selectIndexPath.allKeys containsObject:section]) {
        NSIndexPath *containIndex = [self.selectIndexPath objectForKey:section];
        DDDetailsSpecValueCell *cell = (DDDetailsSpecValueCell *)[collectionView cellForItemAtIndexPath:containIndex];
        cell.valueSelected = NO;
    }

    KKLog(@"specValue == %@",specValue.spec_value);
    DDDetailsSpecValueCell *cell = (DDDetailsSpecValueCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.valueSelected = YES;
    [self.selectIndexPath setObject:indexPath forKey:[NSString stringWithFormat:@"%ld",indexPath.section]];
    [self.selectSpec setObject:specValue.spec_value forKey:spec.spec_name];
    [self.selectSpecValue setObject:specValue.spec_value_id forKey:spec.spec_name];
}
#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDGoodsSpec *spec = self.specSet.specList[indexPath.section];
    DDGoodsSpecValue *specValue = spec.valueList[indexPath.row];
    NSString *value = specValue.spec_value;
    CGFloat width = [ToolKit widthWithFont:[UIFont systemFontOfSize:13.0] height:30 text:value];
    width = width>=65?width:65;
    CGFloat height = 30;
    return (CGSize){width,height};
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
    headerView.backgroundColor =[UIColor clearColor];
    
    if (indexPath.section<self.specSet.specList.count) {
        DDGoodsSpec *spec = self.specSet.specList[indexPath.section];
        DDSpecNormalHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SpecNormalHeader" forIndexPath:indexPath];
        header.keyLbl.text = spec.spec_name;
        headerView = header;
    }else{
        weak_Self(self);
        DDSpecCountHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SpecCountHeader" forIndexPath:indexPath];
        headerView = header;
        [header headerCountBarShowKeyboard:^(CGFloat distance) {
            [weakSelf.specCollection setContentOffset:CGPointMake(0, distance) animated:YES];
        } display:^(CGFloat distance) {
            [weakSelf.specCollection setContentOffset:CGPointMake(0, 0) animated:YES];
        }];
        self.specCountHeader = header;
    }

    return headerView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section<self.specSet.specList.count) {
        return CGSizeMake(ScreenWidth, 25);
    }else{
        return CGSizeMake(ScreenWidth, 35);
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 10, 5, 5);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}

- (void)setSpecSet:(DDGoodsSpecSet *)specSet
{
    _specSet = specSet;
    [self.specCollection reloadData];
}
- (void)setGoodsPic:(NSString *)goodsPic
{
    _goodsPic = goodsPic;
    [self.goodsIcon sd_setImageWithURL:[NSURL URLWithString:goodsPic] placeholderImage:nil];
}
- (void)setGoodsPrice:(NSNumber *)goodsPrice
{
    _goodsPrice = goodsPrice;
    self.priceLbl.text = FormatString(@"$%@", goodsPrice);
}
- (NSString *)goodsNum
{
    return self.specCountHeader.inputCount;
}
- (void)setGoodsSn:(NSString *)goodsSn
{
    _goodsSn = goodsSn;
    _codeLbl.text = FormatString(@"Goods Sn:%@", goodsSn);
}
@end

@interface DDDetailsSpecValueCell()
@property (strong, nonatomic) UIButton *valueBtn;
@end

@implementation DDDetailsSpecValueCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        weak_Self(self);
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"Golden" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:13.0];
        [self.contentView addSubview:btn];
        btn.layer.cornerRadius = 3.0;
        btn.layer.borderColor = RGBColor(200, 200, 200).CGColor;
        btn.layer.borderWidth = 1.0;
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:kRedColor forState:UIControlStateSelected];
        btn.enabled = NO;
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.contentView);
        }];
        self.valueBtn = btn;
    }
    return self;
}
- (void)setSpecValue:(NSString *)specValue
{
    _specValue = specValue;
    [self.valueBtn setTitle:specValue forState:UIControlStateNormal];
}
- (void)setValueSelected:(BOOL)valueSelected
{
    _valueSelected = valueSelected;
    self.valueBtn.selected = YES;
    if (valueSelected) {
        self.valueBtn.layer.borderColor = kRedColor.CGColor;
        [self.valueBtn setTitleColor:kRedColor forState:UIControlStateNormal];
    }else{
        self.valueBtn.layer.borderColor = RGBColor(200, 200, 200).CGColor;
        [self.valueBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
}
@end
